package com.wqj.ride.happyriding.nav.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.constraint.ConstraintLayout;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.enums.IconType;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.wqj.ride.happyriding.R;
import com.wqj.ride.happyriding.bluetooth.bt.BtDevicesActivity;
import com.wqj.ride.happyriding.network.WeatherManager;
import com.wqj.ride.happyriding.network.bean.WeatherInfo;
import com.wqj.ride.happyriding.network.listener.WeatherResponseListener;
import com.wqj.ride.happyriding.service.HappyRiddingService;
import com.wqj.ride.happyriding.service.listener.NaviInfoUpdateListener;
import com.wqj.ride.happyriding.service.listener.TimerListener;

import java.text.DecimalFormat;

public class CustomRouteNaviActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "CustomRouteNaviActivity";
    private static final byte UNIT_M = 0;
    private static final byte UNIT_KM = 1;

    private long mStartTime = 0l;

    Button mContinueView;
    Button mPauseView;
    Button mStopView;
    Button mConnectView;
    ImageView directionView;
    TextView retainView;
    TextView speedView;
    TextView maxSpeedView;
    TextView totalRetainDistanceTagView;
    TextView totalRetainDistanceView;
    TextView totalRetainTimeView;
    TextView rideDistanceTagView;
    TextView rideDistanceView;
    TextView totalSpendTimeView;
    TextView dragTitleView;
    SlidingUpPanelLayout slidingLayout;
    ConstraintLayout mainLayout;
    PowerManager.WakeLock mWakeLock;
    private HappyRiddingService.MyBinder mService;
    private NaviInfoUpdateListener mNaviInfoUpdateListener;
    private TimerListener mTimerListener;

    private NaviLatLng mLastLatLng = null; //计算运动里程
    private int mRideDistance = 0;

    private int mMaxSpeed = 0;
    private Boolean isServiceBond = false;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            Log.e(TAG, "onServiceConnected");
            mService = (HappyRiddingService.MyBinder) service;
            isServiceBond = true;

            mService.setNaviInfoUpdateListener(mNaviInfoUpdateListener);
            mService.setTimerListener(mTimerListener);
            startNavi();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "onServiceDisconnected");
            isServiceBond = false;
        }
    };

    void initView() {
        mainLayout                  = (ConstraintLayout) findViewById(R.id.mainView);
        directionView               = (ImageView) findViewById(R.id.directionView);
        retainView                  = (TextView) findViewById(R.id.retainView);
        speedView                   = (TextView) findViewById(R.id.speedView);
        maxSpeedView                = (TextView) findViewById(R.id.maxSpeedView);
        totalRetainTimeView         = (TextView) findViewById(R.id.totalRetainTimeView);
        rideDistanceTagView         = (TextView) findViewById(R.id.rideDistanceTagView);
        rideDistanceView            = (TextView) findViewById(R.id.rideDistanceView);
        totalSpendTimeView          = (TextView) findViewById(R.id.totalSpendTimeView);
        dragTitleView               = (TextView) findViewById(R.id.dragTitleView);
        slidingLayout               = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
        mContinueView               = (Button) findViewById(R.id.continueView);
        mPauseView                  = (Button) findViewById(R.id.pauseView);
        mStopView                   = (Button) findViewById(R.id.stopView);
        mConnectView                = (Button) findViewById(R.id.connectBluetoothView);
        totalRetainDistanceTagView  = (TextView) findViewById(R.id.totalRetainDistanceTagView);
        totalRetainDistanceView     = (TextView) findViewById(R.id.totalRetainDistanceView);
    }

    private void initListener() {
        mainLayout.setOnClickListener(this);
        slidingLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(View panel, float slideOffset) {
            }

            @Override
            public void onPanelStateChanged(View panel
                    , SlidingUpPanelLayout.PanelState previousState
                    , SlidingUpPanelLayout.PanelState newState) {
                Log.d("wqj", "view: " + panel + ", previousState: "
                        + previousState + ", newState: " + newState);
                if (newState == SlidingUpPanelLayout.PanelState.EXPANDED) {
                    PropertyValuesHolder transX = PropertyValuesHolder
                            .ofFloat("translationY", 0f, -600f);
                    ObjectAnimator anim1 = ObjectAnimator
                            .ofPropertyValuesHolder(directionView, transX).setDuration(100);
                    ObjectAnimator anim2 = ObjectAnimator
                            .ofPropertyValuesHolder(retainView, transX).setDuration(100);
                    AnimatorSet animSet = new AnimatorSet();
                    animSet.play(anim1).after(anim2);
                    animSet.start();
                    directionView.setVisibility(View.INVISIBLE);
                } else if (newState == SlidingUpPanelLayout.PanelState.COLLAPSED) {
                    PropertyValuesHolder transX = PropertyValuesHolder
                            .ofFloat("translationY", -600f, 0f);
                    ObjectAnimator anim1 = ObjectAnimator
                            .ofPropertyValuesHolder(directionView, transX).setDuration(100);
                    ObjectAnimator anim2 = ObjectAnimator
                            .ofPropertyValuesHolder(retainView, transX).setDuration(100);
                    AnimatorSet animSet = new AnimatorSet();
                    animSet.play(anim1).after(anim2);
                    animSet.start();
                    directionView.setVisibility(View.VISIBLE);
                }
            }
        });

        mNaviInfoUpdateListener = new NaviInfoUpdateListener() {
            @Override
            public void onNaviInfoUpdate(NaviInfo naviInfo) {
                refreshUI(naviInfo);
            }
        };

        mTimerListener = new TimerListener() {
            @Override
            public void onTimerUpdate(Long time) {
                String hh = new DecimalFormat("00").format(time / 3600);
                String mm = new DecimalFormat("00").format(time % 3600 / 60);
                String ss = new DecimalFormat("00").format(time % 60);
                String timeFormat = new String(hh + ":" + mm + ":" + ss);

                totalSpendTimeView.setText(timeFormat);
            }
        };
        mContinueView.setOnClickListener(this);
        mPauseView.setOnClickListener(this);
        mStopView.setOnClickListener(this);
        mConnectView.setOnClickListener(this);
    }

    private String mDestination;
    private void initUI() {
        WeatherManager.getInstance().getWeather("上海", new WeatherResponseListener() {
            @Override
            public void onResponse(WeatherInfo w) {
                Log.d(TAG, "weather: " + w.toString());

            }
        });

        Intent intent = getIntent();

        mDestination = intent.getStringExtra("Destination");
        dragTitleView.setText("我的位置 -> " + mDestination);
        mConnectView.setVisibility(View.GONE);
        // slidingLayout.setAnchorPoint(0.5f);
    }

    @SuppressLint("InvalidWakeLockTag")
    private void initData() {
        PowerManager pm= (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager
                .ON_AFTER_RELEASE|PowerManager.PARTIAL_WAKE_LOCK,"NaviActivity");
        mWakeLock.acquire();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_route_navi);

        initView();

        initListener();

        initUI();

        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");

        if (!isServiceBond) {
            Intent intent = new Intent(this, HappyRiddingService.class);

            startService(intent);

            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        if (isServiceBond) {
            mService.setNaviInfoUpdateListener(mNaviInfoUpdateListener);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
        if (isServiceBond) {
            mService.removeNaviInfoUpdateListener();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        mWakeLock.release();

        if (isServiceBond) {
            unbindService(mServiceConnection);
            isServiceBond = false;
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent;
        //super.onBackPressed();
        if (HappyRiddingService.Companion.getNAVI_STATUS_STOPPED() == mNavStatus
                || HappyRiddingService.Companion.getNAVI_STATUS_FINISHED() == mNavStatus) {
            intent = new Intent(getApplicationContext()
                    , RouteShowActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        long currentTime = System.currentTimeMillis();
        if ((currentTime - mStartTime) >= 2000) {
            Toast.makeText(this, getString(R.string.info_confirm_exit)
                    , Toast.LENGTH_SHORT).show();
            mStartTime = currentTime;
        } else {
            mService.stopNavi();
            intent = new Intent(getApplicationContext()
                    , RouteShowActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.continueView:
            {
                mService.resumeNavi();
                setStatus(HappyRiddingService.Companion.getNAVI_STATUS_NAVING());
            }
            break;
            case R.id.pauseView:
            {
                mService.pauseNavi();
                setStatus(HappyRiddingService.Companion.getNAVI_STATUS_PAUSED());
            }
            break;
            case R.id.stopView:
            {
                stopNaviBtnClicked();
            }
            break;
            case R.id.connectBluetoothView:
            {
                Intent intent = new Intent(this, BtDevicesActivity.class);
                startActivity(intent);
            }
            break;
            case R.id.mainView:
            {
                continueClick();
            }
        }
    }

    void startNavi() {
        Intent intent = getIntent();

        int naviType = intent.getIntExtra("NaviType", NaviType.EMULATOR);

        mService.startNavi(naviType);
        setStatus(HappyRiddingService.Companion.getNAVI_STATUS_NAVING());

        mLastLatLng = null; //计算运动里程
        mRideDistance = 0;
    }

    private int mNavStatus = HappyRiddingService.Companion.getNAVI_STATUS_NAVING();
    private void setStatus(int status) {
        mNavStatus = status;
        if (HappyRiddingService.Companion.getNAVI_STATUS_NAVING() == status) {
            mContinueView.setVisibility(View.INVISIBLE);
            mPauseView.setVisibility(View.VISIBLE);
            mStopView.setVisibility(View.VISIBLE);
        }
        else if (HappyRiddingService.Companion.getNAVI_STATUS_PAUSED() == status) {
            mContinueView.setVisibility(View.VISIBLE);
            mPauseView.setVisibility(View.INVISIBLE);
            mStopView.setVisibility(View.INVISIBLE);
        }
        else if (HappyRiddingService.Companion.getNAVI_STATUS_STOPPED() == status) {
            mContinueView.setVisibility(View.INVISIBLE);
            mPauseView.setVisibility(View.INVISIBLE);
            mStopView.setVisibility(View.INVISIBLE);
            // mConnectView.setVisibility(View.INVISIBLE);
        }
        else if (HappyRiddingService.Companion.getNAVI_STATUS_FINISHED() == status) {
            mContinueView.setVisibility(View.INVISIBLE);
            mPauseView.setVisibility(View.INVISIBLE);
            mStopView.setVisibility(View.INVISIBLE);
            // mConnectView.setVisibility(View.INVISIBLE);
        }
    }

    private void stopNaviBtnClicked() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setIcon(R.mipmap.location_bike_icon);
        normalDialog.setTitle("停止导航");
        normalDialog.setMessage("确定要停止导航么?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mService.stopNavi();
                        setStatus(HappyRiddingService.Companion.getNAVI_STATUS_STOPPED());
                        // finish();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    void refreshUI(NaviInfo naviInfo) {
        int iconType = naviInfo.getIconType();
        int retainDistance = naviInfo.getCurStepRetainDistance();
        int speed = naviInfo.getCurrentSpeed();
        int totalRetainDistance = naviInfo.getPathRetainDistance();
        int totalRetainTime = naviInfo.getPathRetainTime();
        int degree = 0;
        String retainText;
        int hour = 0;
        int minute = 0;
        int second = 0;
        DecimalFormat df=new DecimalFormat("0.00");


        if (null != mLastLatLng) {
            LatLng latLngStart = new LatLng(mLastLatLng.getLatitude(), mLastLatLng.getLongitude());
            LatLng latLngEnd = new LatLng(naviInfo.currentCoord.getLatitude()
                    , naviInfo.currentCoord.getLongitude());
            mRideDistance += AMapUtils.calculateLineDistance(latLngStart, latLngEnd);
        }
        mLastLatLng = naviInfo.currentCoord;

        if (mRideDistance >= 1000) {
            rideDistanceTagView.setText(String.format(getString(R.string.distance)
                    , getString(R.string.unit_km)));
            rideDistanceView.setText("" + df.format((float)mRideDistance / 1000));
        } else {
            rideDistanceView.setText("" + mRideDistance);
            rideDistanceTagView.setText(String.format(getString(R.string.distance)
                    , getString(R.string.unit_m)));
        }

        // Log.d(TAG,  "opt: " + iconType + ", distance: " + retainDistance);
        speedView.setText("" + speed);
        if (mMaxSpeed < speed) {
            mMaxSpeed = speed;
            maxSpeedView.setText("" + mMaxSpeed);
        }
        if (totalRetainDistance >= 1000) {
            totalRetainDistanceView
                    .setText("" + df.format((float)totalRetainDistance / 1000));
            totalRetainDistanceTagView.setText(String.format(getString(R.string.remain_distance)
                    , getString(R.string.unit_km)));
        } else {
            totalRetainDistanceView.setText("" + totalRetainDistance);
            totalRetainDistanceTagView.setText(String.format(getString(R.string.remain_distance)
                    , getString(R.string.unit_m)));
        }
        if (0 == totalRetainDistance) {
            mService.stopNavi();
            setStatus(HappyRiddingService.Companion.getNAVI_STATUS_FINISHED());
        }

        Log.d("wqj", "retain time: " + totalRetainTime);
        if (totalRetainTime >= 3600) {
            hour = totalRetainTime / 3600;
            totalRetainTime = totalRetainTime - hour * 3600;
        } if (totalRetainTime >= 60) {
            minute = totalRetainTime / 60;
            totalRetainTime = totalRetainTime - minute * 60;
        } if (totalRetainTime >= 0) {
            second = totalRetainTime;
        }
        totalRetainTimeView.setText(new DecimalFormat("00").format(hour)
                + ":"
                + new DecimalFormat("00").format(minute)
                + ":"
                + new DecimalFormat("00").format(second));
        directionView.setRotation(0);
        switch (iconType) {
            case IconType.STRAIGHT: {
                Log.d(TAG, "直行" + retainDistance + "m");
                retainText = "直行" + retainDistance + "m";
                degree = 0;
            }
            break;
            // 右转
            case IconType.RIGHT: {
                Log.d(TAG, "右转");
                retainText = "右转" + retainDistance + "m";
                degree = 90;
            }
            break;
            // 右前方转
            case IconType.RIGHT_FRONT: {
                Log.d(TAG, "右前方转");
                retainText = "右前方转" + retainDistance + "m";
                degree = 45;
            }
            break;
            // 右后方转
            case IconType.RIGHT_BACK: {
                Log.d(TAG, "右后方转");
                retainText = "右后方转" + retainDistance + "m";
                degree = 135;
            }
            break;
            // 左转
            case IconType.LEFT: {
                Log.d(TAG, "左转");
                retainText = "左转" + retainDistance + "m";
                degree = -90;
            }
            break;
            // 左前方转
            case IconType.LEFT_FRONT: {
                Log.d(TAG, "左前方转");
                retainText = "左前方转" + retainDistance + "m";
                degree = -45;
            }
            break;
            // 左后方转
            case IconType.LEFT_BACK: {
                Log.d(TAG, "左后方转");
                retainText = "左后方转" + retainDistance + "m";
                degree = -135;
            }
            break;
            // 左转掉头
            case IconType.LEFT_TURN_AROUND: {
                Log.d(TAG, "左转掉头");
                retainText = "左转掉头" + retainDistance + "m";
                degree = 225;
            }
            break;
            // 到达途经点
            case IconType.ARRIVED_WAYPOINT: {
                Log.d(TAG, "到达途经点");
                retainText = "到达途经点";
                // ToastUtil.show(this.getBaseContext(),"到达途经点");
            }
            break;
            // 减速慢行
            case IconType.SLOW: {
                Log.d(TAG, "减速慢行");
                retainText = "减速慢行";
                // ToastUtil.show(this.getBaseContext(),"减速慢行");
            }
            break;
            // 到达目的地
            case IconType.ARRIVED_DESTINATION: {
                Log.d(TAG, "到达" + mDestination);
                retainText = "到达" + mDestination;
            }
            break;
            default: {
                retainText = "";
            }
        }
        retainView.setText(retainText);
        if (0 != degree) {
            directionView.setRotation(degree);
        }
    }

    final static int COUNTS = 10;//点击次数
    final static long DURATION = 3 * 1000;//规定有效时间
    long[] mHits = new long[COUNTS];

    /**
     * 连续点击多次退出
     */
    private void continueClick() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//System.currentTimeMillis()

        if ((mHits[mHits.length - 1] - mHits[0] <= DURATION)) {
            mConnectView.setVisibility(View.VISIBLE);
        }
    }
}
